<?php

/*
 *  @author     Subha <subhasundar.das@gmail.com.com>
 *  @version    1.0
 */


use Symfony\Component\Console\Command\Command;
use Laravel\File;

class DatabaseBackup extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'db:backup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Backup mySQL database';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct() {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public static  function fire() {
        //$this->info('Database Backup Started');
        $host = Config::get('database.connections.mysql.host');
        $database = Config::get('database.connections.mysql.database');
        $username = Config::get('database.connections.mysql.username');
        $password = Config::get('database.connections.mysql.password');
        $backupPath = path('storage') . "database/";
        $backupFileName = $database . "-" . date("Y-m-d-H-i-s") . '.zip';

        //for linux replace the path with /usr/local/bin/mysqldump (The path might varies).
        //$path = "c:\\xampp\mysql\bin\mysqldump";
        $path = "mysqldump";

        //without password
        //$command = $path . " -u " . $username . " " . $database . " > " . $backupPath . $backupFileName;
        //with password
        $command = $path . " -u " . $username . " -p" . $password . " " . $database . " | gzip -9 > " . $backupPath . $backupFileName;
        //print $command;
        system($command);

        //--Insert Database (table name: backup_log)
        $fileSize = File::size($backupPath . $backupFileName);
        DB::table('backup_log')->insert(array(
            'file'         => trim($backupFileName),
            'size'          => $fileSize
        ));

        return 'Done ... ' . $backupPath . $backupFileName;

    }

}